use crate::model::system_admin::{SystemAdmin, SystemAdminDto, SystemAdminPageDTO};
use crate::model::RespVO;
use crate::APPLICATION_CONTEXT;
use ntex::web;
use ntex::web::types::{Path, Query};
use ntex::web::{get, post, types::Json, HttpRequest, Responder, ServiceConfig};

/// 管理员列表页面
#[get("/page")]
pub async fn page(dto: Query<SystemAdminPageDTO>) -> impl Responder {
    let page = &APPLICATION_CONTEXT.system_admin_service.page(&dto).await;
    RespVO::from_result(&page).resp_json()
}

/// 管理员详情
#[get("/detail/user_id/{user_id}")]
pub async fn detail(user_id: Path<u32>) -> impl Responder {
    let detail = &APPLICATION_CONTEXT
        .system_admin_service
        .detail(user_id.clone())
        .await;
    RespVO::from_result(&detail).resp_json()
}

/// 创建管理员
#[post("/create")]
pub async fn create(data: Json<SystemAdmin>) -> impl Responder {
    let result = &APPLICATION_CONTEXT
        .system_admin_service
        .create(data.clone())
        .await;
    RespVO::from_result(&result).resp_json()
}

/// 修改管理员
#[post("/update")]
pub async fn update(dto: Json<SystemAdminDto>) -> impl Responder {
    let result = &APPLICATION_CONTEXT
        .system_admin_service
        .update(dto.clone())
        .await;
    RespVO::from_result(&result).resp_json()
}

/// 删除管理员
#[get("/delete/user_id/{user_id}")]
pub async fn delete(user_id: Path<u32>) -> impl Responder {
    let result = &APPLICATION_CONTEXT
        .system_admin_service
        .delete(user_id.clone())
        .await;
    RespVO::from_result(&result).resp_json()
}

/// 获取管理员信息
#[get("/info")]
pub async fn info(req: HttpRequest) -> impl Responder {
    if let Some(user_id) = req.extensions().get::<u32>() {
        let vo = &APPLICATION_CONTEXT.system_admin_service.info(user_id).await;
        return RespVO::from_result(&vo).resp_json();
    }
    RespVO::<String>::from_error_info(250, "登录失败！").resp_json()
}

pub fn system_admin(cfg: &mut ServiceConfig) {
    cfg.service(
        web::scope("/system/admin")
            .service(page)
            .service(detail)
            .service(create)
            .service(update)
            .service(info),
    );
}
